package org.yzh.framework.commons.transform;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

public class ByteBufUtils {

    /**
     * BCC校验(异或校验)
     */
    public static byte bcc(ByteBuf byteBuf) {
        byte cs = 0;
        while (byteBuf.isReadable())
            cs ^= byteBuf.readByte();
        byteBuf.resetReaderIndex();
        return cs;
    }


    /**
     * BCC校验(异或校验)
     */
    public static byte sum(ByteBuf byteBuf) {
        byte cs = 0;
        while (byteBuf.isReadable())
            cs += byteBuf.readUnsignedByte();
        byteBuf.resetReaderIndex();
        return cs;
    }

    /**
     * 高低位互换
     */
    public static ByteBuf reverseByteBuf(ByteBuf source) {
        if(source == null ) return source;
        int start = source.readerIndex();
        int end = source.writerIndex();
        for(int i=start; i < end; i=i+2){
            reverseByte(source, i);
        }
        return source;
    }

    /**
     * 高低位互换
     */
    public static ByteBuf reverseByte(ByteBuf source, int index) {
        byte low = source.getByte(index);
        byte high = source.getByte(index+1 );
        source.setByte(index, high);
        source.setByte(index+1, low);
        return source;
    }


    /**
     * 提取终端号
     * @param source 源报文
     * @return
     */
    public static ByteBuf getLengthByteBuf(ByteBuf source){
        int low = source.readerIndex();
        //提取终端号进行互换
        int terminalStartMark = low + 1;
        return source.slice(terminalStartMark,4);

    }



    /**
     * 提取终端号
     * @param source 源报文
     * @return
     */
    public static ByteBuf getTerminalInfoByteBuf(ByteBuf source){
        int low = source.readerIndex();
        //提取终端号进行互换
        int terminalStartMark = low + 7;
        return  source.slice(terminalStartMark,4);
    }


    /**
     * 提取用户报文
     * @param source 源报文
     * @return 用户区报文
     */
    public static ByteBuf getUserInfoByteBuf(ByteBuf source){
        int low = source.readerIndex();
        int high = source.writerIndex();
        int userEndMark = high - 2;
        int userStartMark = low + 23;
        if(high <= userStartMark)
            return null;
        return source.slice(userStartMark,userEndMark - userStartMark);
    }

    public static void main(String[] args) {
        byte[] buf =  ByteBufUtil.decodeHexDump("0B201511990000750100");
        ByteBuf byteBuf = Unpooled.wrappedBuffer(buf);
        byte b= ByteBufUtils.sum(byteBuf);

        System.out.println(b);
    }

}